import React, { useState, useEffect } from 'react';
import { type RemediationFormData } from '@/types/Remediation';
import { RiskLevel } from '@/types/work';

interface RemediationFormProps {
  initialData?: RemediationFormData;
  onSubmit: (data: RemediationFormData) => void;
  onCancel: () => void;
  title: string;
  submitText: string;
  isFromComplianceItem?: boolean;
}

const RemediationForm: React.FC<RemediationFormProps> = ({
  initialData,
  onSubmit,
  onCancel,
  title,
  submitText,
  isFromComplianceItem = false,
}) => {
  // 表单状态
  const [formData, setFormData] = useState<RemediationFormData>({
    title: '',
    description: '',
    suggestion: '',
    riskLevel: RiskLevel.MEDIUM,
    item_id: '',
    plan_id: '',
  });
  
  // 表单验证错误
  const [errors, setErrors] = useState<{
    title?: string;
    description?: string;
    suggestion?: string;
  }>({});
  
  // 初始化表单数据
  useEffect(() => {
    if (initialData) {
      setFormData(initialData);
    }
  }, [initialData]);
  
  // 处理输入变化
  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // 清除对应字段的错误
    if (errors[name as keyof typeof errors]) {
      setErrors(prev => ({ ...prev, [name]: undefined }));
    }
  };
  
  // 验证表单
  const validateForm = (): boolean => {
    const newErrors: typeof errors = {};
    
    if (!formData.title.trim()) {
      newErrors.title = '检查名称不能为空';
    }
    
    if (!formData.description.trim()) {
      newErrors.description = '检查描述不能为空';
    }
    
    if (!formData.suggestion.trim()) {
      newErrors.suggestion = '整改建议不能为空';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  // 提交表单
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (validateForm()) {
      onSubmit(formData);
    }
  };
  
  return (
    <div className="bg-background p-6 rounded-lg max-w-2xl w-full">
      <h2 className="text-xl font-semibold mb-4">{title}</h2>
      
      {isFromComplianceItem && (
        <p className="text-sm text-muted-foreground mb-4">
          以下信息已根据检查项自动填充，请确认或修改后创建整改项
        </p>
      )}
      
      <form onSubmit={handleSubmit}>
        <div className="space-y-4">
          {/* 检查名称 */}
          <div>
            <label htmlFor="name" className="block text-sm font-medium mb-1">
              检查名称 <span className="text-destructive">*</span>
            </label>
            <input
              type="text"
              id="title"
              name="title"
              value={formData.title}
              onChange={handleChange}
              className={`w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 ${
                errors.title ? 'border-destructive' : ''
              }`}
            />
            {errors.title && (
              <p className="text-destructive text-sm mt-1">{errors.title}</p>
            )}
          </div>
          
          {/* 检查描述 */}
          <div>
            <label htmlFor="description" className="block text-sm font-medium mb-1">
              检查描述 <span className="text-destructive">*</span>
            </label>
            <textarea
              id="description"
              name="description"
              value={formData.description}
              onChange={handleChange}
              rows={4}
              className={`w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 ${
                errors.description ? 'border-destructive' : ''
              }`}
            />
            {errors.description && (
              <p className="text-destructive text-sm mt-1">{errors.description}</p>
            )}
          </div>
          
          {/* 整改建议 */}
          <div>
            <label htmlFor="suggestion" className="block text-sm font-medium mb-1">
              整改建议 <span className="text-destructive">*</span>
            </label>
            <textarea
              id="suggestion"
              name="suggestion"
              value={formData.suggestion}
              onChange={handleChange}
              rows={4}
              className={`w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 ${
                errors.suggestion ? 'border-destructive' : ''
              }`}
            />
            {errors.suggestion && (
              <p className="text-destructive text-sm mt-1">{errors.suggestion}</p>
            )}
          </div>
          
          {/* 风险等级 */}
          <div>
            <label htmlFor="riskLevel" className="block text-sm font-medium mb-1">
              风险等级 <span className="text-destructive">*</span>
            </label>
            <select
              id="riskLevel"
              name="riskLevel"
              value={formData.riskLevel}
              onChange={handleChange}
              className="w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50"
            >
              <option value={RiskLevel.HIGH}>高风险</option>
              <option value={RiskLevel.MEDIUM}>中风险</option>
              <option value={RiskLevel.LOW}>低风险</option>
            </select>
          </div>
        </div>
        
        <div className="flex justify-end space-x-3 mt-6">
          <button
            type="button"
            onClick={onCancel}
            className="px-4 py-2 border rounded-md hover:bg-muted transition-colors"
          >
            取消
          </button>
          <button
            type="submit"
            className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary-hover transition-colors"
          >
            {submitText}
          </button>
        </div>
      </form>
    </div>
  );
};

export default RemediationForm;
